package com.example.demo.web.services;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.async.DeferredResult;

import com.example.demo.web.Entity.KeyEntity;
import com.example.demo.web.Entity.LockEntity;
import com.example.demo.web.Entity.LockMissionDetailEntity;
import com.example.demo.web.Entity.LockOpenLogEntity;
import com.example.demo.web.Entity.LockUserEntity;
import com.example.demo.web.Entity.MissionEntity;
import com.example.demo.web.Entity.OrganizationEntity;
import com.example.demo.web.Entity.UserEntity;
import com.example.demo.web.Entity.UserLogEntity;
import com.example.demo.web.Entity.UserRoleUnionOrg;
import com.example.demo.web.dao.LockDAO;
import com.example.demo.web.dao.MissionDAO;
import com.example.demo.web.dao.UserDAO;
import com.example.demo.web.util.XinLongUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;


@Service
@Transactional
public class LockService {
	private Logger log = LogManager.getLogger(LockService.class);
	private LockDAO lockDao;
	
    @Autowired
    public void setlockDao(LockDAO lockDao){
        this.lockDao =lockDao;
    }
    
    private UserDAO userDao;
    @Autowired
    public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}
    
    private MissionDAO missionDao;
    @Autowired
	public void setMissionDao(MissionDAO missionDao) {
		this.missionDao = missionDao;
	}

	public String getlocklist(String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	ArrayNode rootnode = mapper.createArrayNode();
    	com.fasterxml.jackson.databind.JsonNode rootNode;	
    	int pageNumber = 0;
    	int pageSize = 0;
    	String orgname = "";
    	String opername = "";
    	String locksn = "";
    	try {
			rootNode = mapper.readTree(jsonstr);
			pageNumber =rootNode.get("pageNumber").asInt();
			pageSize=rootNode.get("pageSize").asInt();
			orgname =rootNode.get("orgname").asText();
			opername =rootNode.get("opername").asText();
			locksn=rootNode.get("locksn").asText();
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		return mapper.writeValueAsString(resjson);
		}		
    	//判断用户是否为日常管理员
    	int totalcount = 0;
    	if(userDao.findRoleByUsername(sentity.getUsername()) < 3) {
    		//是日常管理员
    		List<OrganizationEntity> suborgs = null;
    		List<LockEntity> locklist = null;
    		if(userDao.isRootOrg(sentity.getOrg_id())) {
    			locklist = lockDao.findAll(pageNumber,pageSize,orgname,opername,locksn);
    			totalcount = lockDao.getCount(orgname,opername,locksn);
    		}else {
    			suborgs = userDao.findSubOrg(sentity.getOrg_id());
    			locklist = lockDao.findAll(pageNumber,pageSize,orgname,opername,locksn,suborgs);
    			totalcount = lockDao.getCount(orgname,opername,locksn,suborgs);
    		}
        	if(locklist != null && locklist.size()> 0){
    			ObjectNode tjson = null;
    			for(LockEntity sys : locklist){
    				tjson = mapper.createObjectNode();
    				tjson.put("id", sys.getId());
        			tjson.put("descriptor", sys.getDescriptor());
        			tjson.put("locksn", sys.getLocksn());
        			tjson.put("operators", sys.getOperators());
        			tjson.put("oper_reals", sys.getOper_reals());
        			tjson.put("authed", sys.getAuthed());
        			tjson.put("regtime", sys.getRegtime());        			
        			tjson.put("orgname", sys.getOrgname());
        			tjson.put("area", sys.getArea());
        			tjson.put("boxid", sys.getBoxid());
        			tjson.put("opentype", sys.getOpentype());
        			tjson.put("locktype", sys.getLocktype());
        			tjson.put("electricity", sys.getElectricity());
        			tjson.put("orgid", sys.getOrgid());
        			rootnode.add(tjson);
        		}
    		} 
        	
    	}else {
    		//不是日常管理员
        	List<LockEntity> locklist = lockDao.findByUser(pageNumber,pageSize,locksn,sentity.getUsername());
        	if(locklist != null && locklist.size()> 0){
    			ObjectNode tjson = null;
    			for(LockEntity sys : locklist){
    				tjson = mapper.createObjectNode();
    				tjson.put("id", sys.getId());
        			tjson.put("descriptor", sys.getDescriptor());
        			tjson.put("locksn", sys.getLocksn());
        			tjson.put("operators", sys.getOperators());
        			tjson.put("oper_reals", sys.getOper_reals());
        			tjson.put("authed", sys.getAuthed());  
        			tjson.put("regtime", sys.getRegtime());
        			tjson.put("orgname", sys.getOrgname());
        			tjson.put("area", sys.getArea());
        			tjson.put("boxid", sys.getBoxid());
        			tjson.put("opentype", sys.getOpentype());
        			tjson.put("locktype", sys.getLocktype());
        			tjson.put("electricity", sys.getElectricity());
        			tjson.put("orgid", sys.getOrgid());
        			rootnode.add(tjson);
        		}
    		} 
        	totalcount = lockDao.getfindByUserCount(locksn,sentity.getUsername());
    	}
    	
    	
    	resjson.put("status", "1");
    	resjson.put("totalCount", totalcount);
    	resjson.put("pageSize", pageSize);
    	resjson.put("datalist", rootnode);
    	
    	return mapper.writeValueAsString(resjson);  
    }
    
    public void _insertlock(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request,HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	LockEntity elock = new LockEntity();
    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String locksn = "";   	
    	String area = "";
    	String boxid = "";
    	String orgid = "";
    	String descriptor = "";
    	String ckname = "";
    	int opentype = 0;
    	int locktype = 0;
    	JsonNode childrenNode = null;
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		locksn =rootNode.get("locksn").asText();
    		area = rootNode.get("area").asText();
    		boxid = rootNode.get("boxid").asText();
    		orgid = rootNode.get("orgid").asText();
			descriptor = rootNode.get("descriptor").asText();
			ckname = rootNode.get("ckname").asText();
			opentype = rootNode.get("opentype").asInt();
			locktype = rootNode.get("locktype").asInt();
			childrenNode = rootNode.path("operators");  
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	
    	//权限判断
    	/*resjson = XinLongUtil.OptAuth("",jsonstr, sentity);
		if(!resjson.get("status").asText().equals("1210")){
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}*/
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/锁具管理/添加编辑");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_insertlock");
		ulog.setOrgid(sentity.getOrg_id());

		String uId = UUID.randomUUID().toString().replace("-", "");
		elock.setId(uId);
		elock.setRegtime(dateFormat.format(date));
		elock.setArea(area);
		elock.setBoxid(boxid);
		elock.setCname(ckname);
		elock.setDescriptor(descriptor);
		elock.setLocksn(locksn);
		elock.setOpentype(opentype);
		elock.setLocktype(locktype);
		elock.setOrgid(orgid);
		elock.setAuthed(0);
		int flag = lockDao.savelock(elock);
		if(flag == 0){
			resjson.put("status", "0");
			resjson.put("desc", "添加锁具失败!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}else if(flag == 2) {
			resjson.put("status", "0");
			resjson.put("desc", "重复的锁具识别码!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}
		//添加锁具使用人信息
		//LockOperatorEntity lockoperator = new LockOperatorEntity();
		Iterator<JsonNode> it = childrenNode.iterator();
		int i = 0;
		StringBuilder sb = new StringBuilder();
		StringBuilder sbrealname = new StringBuilder();
		
    	while(it.hasNext()){
    		JsonNode jnode = it.next();
    		if(locktype == 1) {
    			//主管锁,使用人需为主管
    			if(userDao.findRoleByUsername(jnode.get("username").asText()) != 3) {
    				resjson.put("status", "0");
    				resjson.put("desc", "主管锁使用人必须为主管,[" + jnode.get("username").asText() + "]不是主管!");
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    				deferredResult.setResult(mapper.writeValueAsString(resjson));
    	    		return;
    			}
    		}
    		if(i == 0) {
    			sb.append(jnode.get("username").asText());
    			sbrealname.append(jnode.get("oper_reals").asText());
    		}else {
    			sb.append("," + jnode.get("username").asText());
    			sbrealname.append("," + jnode.get("oper_reals").asText());
    		}
    		i++;
    	}
    	
    	LockUserEntity lockuser = new LockUserEntity();
		lockuser.setId(UUID.randomUUID().toString().replace("-", ""));
		lockuser.setLocksn(locksn);
		lockuser.setOperators(sb.toString());
		lockuser.setOper_reals(sbrealname.toString());
		lockuser.setActive(0);
		lockuser.setOpentype(opentype);
		lockuser.setLocktype(locktype);
		if(lockDao.insertLockuser(lockuser) == 0) {
			resjson.put("status", "0");
			resjson.put("desc", "添加锁具使用人信息失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}
		resjson.put("status", "1");
		resjson.put("desc", "成功!");
		ulog.setDescriptor("锁具[" + locksn + "]被添加");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);

		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _updatelock(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	String locksn = "";    	
    	String area = "";
    	String boxid = "";
    	String orgid = "";
    	String descriptor = "";
    	String ckname = "";
    	int opentype = 0;
    	int locktype = 0;
    	JsonNode childrenNode = null;
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		locksn =rootNode.get("locksn").asText();
    		area = rootNode.get("area").asText();
    		boxid = rootNode.get("boxid").asText();
    		orgid =rootNode.get("orgid").asText();
			descriptor = rootNode.get("descriptor").asText();
			ckname = rootNode.get("ckname").asText();
			opentype = rootNode.get("opentype").asInt();
			locktype = rootNode.get("locktype").asInt();
			childrenNode = rootNode.path("operators");
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/锁具管理/编辑");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setMethod("_updatelock");

    	try{
    		LockEntity elock = lockDao.findBySn(locksn);
    		if(elock == null) {
    			resjson.put("status", "0");
    			resjson.put("desc", "找不到锁具信息!");
    			//TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
    		}
    		XinLongUtil.xinLongUtil.printlog(log,"更新锁具信息:"+ locksn);
    		LockUserEntity lockuser = lockDao.findLockUserByLock(locksn);
        	if(lockuser == null) {
        		resjson.put("status", "0");
    			resjson.put("desc", "找不到锁具使用人信息!");
    			//TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
        	}
        	if(lockuser.getActive() == 1) {
        		//锁具已被授权,需先停止授权
        		resjson.put("status", "0");
    			resjson.put("desc", "锁具已被授权,需先停止授权再进行编辑!");
    			//TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
        	}
    		ulog.setCreate_check_userid(ckname);
    		elock.setArea(area);
    		elock.setBoxid(boxid);
			elock.setCname(ckname);
			elock.setDescriptor(descriptor);
			elock.setOrgid(orgid);
			elock.setOpentype(opentype);
			elock.setLocktype(locktype);
    		if(lockDao.updatelock(elock) == 0){
    			resjson.put("status", "0");
    			resjson.put("desc", "更新锁具信息失败!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
    		}
    		//删除原有使用人
    		/*if(lockDao.deleteLockOperator(locksn) == -1) {
    			resjson.put("status", "0");
    			resjson.put("desc", "删除原锁具使用人信息失败!");
    			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
    		}
    		LockOperatorEntity lockoperator = new LockOperatorEntity();*/
    		//更新锁具使用人
    		Iterator<JsonNode> it = childrenNode.iterator();
    		int i = 0;
    		StringBuilder sb = new StringBuilder();
    		StringBuilder sbrealname = new StringBuilder();
        	while(it.hasNext()){
        		JsonNode jnode = it.next();
        		if(locktype == 1) {
        			//主管锁,使用人需为主管
        			if(userDao.findRoleByUsername(jnode.get("username").asText()) != 3) {
        				resjson.put("status", "0");
        				resjson.put("desc", "主管锁使用人必须为主管,[" + jnode.get("username").asText() + "]不是主管!");
        				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        				deferredResult.setResult(mapper.writeValueAsString(resjson));
        	    		return;
        			}
        		}
        		if(i == 0) {
        			sb.append(jnode.get("username").asText());
        			sbrealname.append(jnode.get("oper_reals").asText());
        		}else {
        			sb.append("," + jnode.get("username").asText());
        			sbrealname.append("," + jnode.get("oper_reals").asText());
        		}
        		i++;
        	}
        	
        	lockuser.setOperators(sb.toString());
        	lockuser.setOper_reals(sbrealname.toString());
        	lockuser.setOpentype(opentype);
        	lockuser.setLocktype(locktype);
        	if(lockDao.updatelockuserActive(lockuser) == 0) {
        		resjson.put("status", "0");
    			resjson.put("desc", "更新锁具使用人信息失败!");
    			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
        	}
        	
    		
    	}catch(EmptyResultDataAccessException er){
    		resjson.put("status", "0");
			resjson.put("desc", "找不到该锁具!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}catch(Exception e){
    		resjson.put("status", "2");
			resjson.put("desc", "未知异常!");
			ulog.setDescriptor(e.getMessage());
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			log.error(e.getMessage());
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	resjson.put("status", "1");
    	resjson.put("desc", "成功!");
    	ulog.setDescriptor("锁具[" + locksn + "]被编辑");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _lockDelete(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode resjson = mapper.createObjectNode();  
		String locksn="";
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/锁具管理/删除");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("_lockDelete");
		ulog.setOrgid(sentity.getOrg_id());
    	com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			locksn=rootNode.get("locksn").asText();
			ulog.setCreate_check_userid(rootNode.get("ckname").asText());
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}		
		/*resjson = XinLongUtil.OptAuth(id,jsonstr, sentity);
		if(!resjson.get("status").asText().equals("1210")){
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}*/		
    	
    	if(lockDao.delete(locksn) == 0){
    		resjson.put("status", "0");
    		resjson.put("desc", "删除锁具失败!");
    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ulog.setDescriptor("删除锁具失败");
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
    	}
    	//删除lock_user记录
    	LockUserEntity lockuser = lockDao.findLockUserByLock(locksn);
    	if(lockuser != null) {
    		if(lockDao.deleteuserBylock(locksn) == 0) {
    			resjson.put("status", "0");
        		resjson.put("desc", "删除锁具授权信息失败!");
        		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			ulog.setDescriptor("删除锁具失败");
    			ulog.setProceed("操作失败");
    			XinLongUtil.saveUserLog(ulog);
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
    		}
    	}

		ulog.setDescriptor("锁具[" + locksn + "]被删除");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
    	resjson.put("status", "1");
		resjson.put("desc", "成功!");
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _lockOff(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode resjson = mapper.createObjectNode();  
		String locksn="";
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/锁具管理/报废");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("_lockOff");
		ulog.setOrgid(sentity.getOrg_id());
    	com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			locksn=rootNode.get("locksn").asText();
			ulog.setCreate_check_userid(rootNode.get("ckname").asText());
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}		
		/*resjson = XinLongUtil.OptAuth(id,jsonstr, sentity);
		if(!resjson.get("status").asText().equals("1210")){
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}*/		
	
    	if(lockDao.offlock(locksn,dateFormat.format(date),sentity.getUsername()) == 0){
    		resjson.put("status", "0");
    		resjson.put("desc", "报废锁具失败!");
    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ulog.setDescriptor("报废锁具失败");
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
    	}
    	//删除lock_user记录
    	LockUserEntity lockuser = lockDao.findLockUserByLock(locksn);
    	if(lockuser != null) {
    		if(lockDao.deleteuserBylock(locksn) == 0) {
    			resjson.put("status", "0");
        		resjson.put("desc", "删除锁具授权信息失败!");
        		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			ulog.setDescriptor("删除锁具失败");
    			ulog.setProceed("操作失败");
    			XinLongUtil.saveUserLog(ulog);
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
    		}
    	}
    	/*if(lockDao.deleteLockOperator(locksn) == -1) {
    		resjson.put("status", "0");
    		resjson.put("desc", "删除锁具使用人信息失败!");
    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ulog.setDescriptor("删除锁具失败");
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
    	}
    	if(lockDao.deleteLockAuther(locksn) == -1) {
    		resjson.put("status", "0");
    		resjson.put("desc", "删除锁具授权信息失败!");
    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ulog.setDescriptor("删除锁具失败");
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
    	}*/
		ulog.setDescriptor("锁具[" + locksn + "]被报废");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
    	resjson.put("status", "1");
		resjson.put("desc", "成功!");
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _getOpenLogs(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode resjson = mapper.createObjectNode();  
		ArrayNode rootnode = mapper.createArrayNode();
		String locksn="";
		String orgname="";
		String keysn="";
		String operator="";
		int pageNumber = 0;
    	int pageSize = 0;
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("系统管理/日志管理/开锁记录");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("_getOpenLogs");
		ulog.setOrgid(sentity.getOrg_id());
    	com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			locksn=rootNode.get("locksn").asText();
			orgname=rootNode.get("orgname").asText();
			keysn=rootNode.get("keysn").asText();
			operator=rootNode.get("operator").asText();
			pageNumber=rootNode.get("pageNumber").asInt();
			pageSize=rootNode.get("pageSize").asInt();
			ulog.setCreate_check_userid(rootNode.get("ckname").asText());
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	
		List<LockOpenLogEntity> loglist = null;
		int totalcount = 0;
		if(userDao.findRoleByUsername(sentity.getUsername()) < 3) {
			List<OrganizationEntity> suborgs = null;
    		
    		if(userDao.isRootOrg(sentity.getOrg_id())) {
    			loglist = lockDao.findOpenLogBySearch(pageNumber,pageSize,operator,locksn,keysn,orgname);
    			totalcount = lockDao.findOpenLogCountBySearch(operator,locksn,keysn,orgname);
    		}else {
    			suborgs = userDao.findSubOrg(sentity.getOrg_id());
    			loglist = lockDao.findOpenLogBySearch(pageNumber,pageSize,operator,locksn,keysn,orgname,suborgs);
    			totalcount = lockDao.findOpenLogCountBySearch(operator,locksn,keysn,orgname,suborgs);
    		}
		}else {
			loglist = lockDao.findOpenLogByOwner(pageNumber, pageSize, sentity.getUsername(), locksn, keysn);
			totalcount = lockDao.findOpenLogCountByOwner(sentity.getUsername(), locksn, keysn);
		}
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	if(loglist != null && loglist.size()> 0){
			ObjectNode tjson = null;
			for(LockOpenLogEntity sys : loglist){
				tjson = mapper.createObjectNode();
				tjson.put("id", sys.getId());
    			tjson.put("keysn", sys.getKeysn());
    			tjson.put("locksn", sys.getLocksn());
    			tjson.put("opentime", sdf.format(sys.getOpentime()));
    			tjson.put("orgname", sys.getOrgname());
    			tjson.put("operator", sys.getOperator());
    			tjson.put("oper_reals", sys.getOper_reals());
    			rootnode.add(tjson);
    		}
		}  
    	
		ulog.setDescriptor("");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		resjson.put("status", "1");
		if(sentity.getUsername().equals("hzwlprevail")){
			resjson.put("needcheck", 0);
		}else{
			resjson.put("needcheck", XinLongUtil.isNeedCheck("系统管理/日志管理/日志导出"));
		}
		resjson.put("totalCount", totalcount);
    	resjson.put("pageSize", pageSize);
    	resjson.put("datalist", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _getLockoffLogs(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode resjson = mapper.createObjectNode();  
		ArrayNode rootnode = mapper.createArrayNode();
		String locksn="";
		String orgname="";
		int pageNumber = 0;
    	int pageSize = 0;
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("系统管理/日志管理/锁具报废记录");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("_getLockoffLogs");
		ulog.setOrgid(sentity.getOrg_id());
    	com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			locksn=rootNode.get("locksn").asText();
			orgname=rootNode.get("orgname").asText();
			pageNumber=rootNode.get("pageNumber").asInt();
			pageSize=rootNode.get("pageSize").asInt();
			ulog.setCreate_check_userid(rootNode.get("ckname").asText());
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}		
		List<OrganizationEntity> suborgs = userDao.findSubOrg(sentity.getOrg_id());
    	List<LockEntity> locklist = lockDao.findOffAll(pageNumber,pageSize,orgname,locksn,suborgs);
    	if(locklist != null && locklist.size()> 0){
			ObjectNode tjson = null;
			for(LockEntity sys : locklist){
				tjson = mapper.createObjectNode();
				tjson.put("id", sys.getId());
    			tjson.put("descriptor", sys.getDescriptor());
    			tjson.put("locksn", sys.getLocksn());
    			tjson.put("offtime", sys.getOfftime());
    			tjson.put("orgname", sys.getOrgname());
    			tjson.put("area", sys.getArea());
    			tjson.put("offuser", sys.getOffuser());
    			rootnode.add(tjson);
    		}
		}  
    	
		ulog.setDescriptor("");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		resjson.put("status", "1");
		if(sentity.getUsername().equals("hzwlprevail")){
			resjson.put("needcheck", 0);
		}else{
			resjson.put("needcheck", XinLongUtil.isNeedCheck("系统管理/日志管理/日志导出"));
		}
		resjson.put("totalCount", lockDao.getOffCount(orgname,locksn,suborgs));
    	resjson.put("pageSize", pageSize);
    	resjson.put("datalist", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
      
    public void getUserLocks(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
		String username = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			username =rootNode.get("username").asText();
		} catch (IOException e1) {
			res.put("status", "2");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}	
		List<LockEntity> locklist = null;
		locklist =lockDao.findLocksByUser(username);
		ObjectNode tjson = null;
    	for(LockEntity ulock : locklist) {
    		tjson = mapper.createObjectNode();
			tjson.put("locksn", ulock.getLocksn());
			tjson.put("area", ulock.getArea());
			rootnode.add(tjson);
    	}
    	res.put("status", "1");
    	res.put("datalist", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void findLocksByLoginUser(DeferredResult<String> deferredResult, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
		com.fasterxml.jackson.databind.JsonNode rootNode;
		
		List<LockEntity> locklist = null;
		locklist =lockDao.findLocksByUser(sentity.getUsername());
		ObjectNode tjson = null;
    	for(LockEntity ulock : locklist) {
    		tjson = mapper.createObjectNode();
			tjson.put("locksn", ulock.getLocksn());
			tjson.put("area", ulock.getArea());
			rootnode.add(tjson);
    	}
    	res.put("status", "1");
    	res.put("datalist", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void getLockUsers(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
		String locksn = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			locksn =rootNode.get("locksn").asText();
		} catch (IOException e1) {
			res.put("status", "2");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}	
		LockUserEntity lockuser = lockDao.findLockUserByLock(locksn);
		if(lockuser == null) {
			res.put("status", "2");
			res.put("desc", "找不到锁具信息!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}
		String[] operators = lockuser.getOperators().split(",");		
		ObjectNode tjson = null;
		UserRoleUnionOrg authuserinfo = null;
    	for(String authuser : operators) {
    		tjson = mapper.createObjectNode();
    		authuserinfo = userDao.findUserByName(authuser);
    		tjson.put("username", authuserinfo.getUsername());
			tjson.put("rolename", userDao.findRolenameByUserId(authuserinfo.getId()));
			tjson.put("oper_reals", authuserinfo.getRealname());
			tjson.put("orgname", authuserinfo.getOrg_name());
			rootnode.add(tjson);
    	}
    	res.put("status", "1");
    	res.put("datalist", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void getLocksByMissionid(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
		ArrayNode usernode = mapper.createArrayNode();
		String missionid = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			missionid =rootNode.get("missionid").asText();
		} catch (IOException e1) {
			res.put("status", "2");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}	
		List<LockUserEntity> locks = null;
		locks =lockDao.findLockUserByMissionid(missionid);
		ObjectNode tjson = null;
    	for(LockUserEntity elock : locks) {
    		tjson = mapper.createObjectNode();
			tjson.put("locksn", elock.getLocksn());
			rootnode.add(tjson);
    	}
    	//获取授权用户信息
    	String[] authusers = locks.get(0).getOperators().split(",");
		UserEntity authuserinfo = null;
    	for(String authuser : authusers) {
    		tjson = mapper.createObjectNode();
    		authuserinfo = userDao.findByUserName(authuser);
    		tjson.put("username", authuserinfo.getUsername());
    		tjson.put("realname", authuserinfo.getRealName());
			tjson.put("rolename", authuserinfo.getRolename());
			usernode.add(tjson);
    	}
    	res.put("status", "1");
    	res.put("datalist", rootnode);
    	res.put("authuser", usernode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void lockauth(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
		String locksn = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			locksn =rootNode.get("locksn").asText();
		} catch (IOException e1) {
			res.put("status", "2");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}	
		LockUserEntity lockuser = null;
		lockuser =lockDao.findLockUserByLock(locksn);
		ObjectNode tjson = null;
		if(lockuser.getActive() == 1) {
			String[] authusers = lockuser.getOperators().split(",");
			UserRoleUnionOrg authuserinfo = null;
	    	for(String authuser : authusers) {
	    		tjson = mapper.createObjectNode();
	    		authuserinfo = userDao.findUserByName(authuser);
	    		tjson.put("username", authuserinfo.getUsername());
				tjson.put("rolename", userDao.findRolenameByUserId(authuserinfo.getId()));
				tjson.put("realname", authuserinfo.getRealname());
				tjson.put("orgname", authuserinfo.getOrg_name());
				rootnode.add(tjson);
	    	}
		}
    	
    	res.put("status", "1");
    	res.put("datalist", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void getLockList_template(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
		String locksn = "";
		String orgid = "";
		String owner = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			locksn =rootNode.get("locksn").asText();
			orgid =rootNode.get("orgid").asText();
			owner =rootNode.get("owner").asText();
		} catch (IOException e1) {
			res.put("status", "2");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}	
		List<LockEntity> locklist = null;
		locklist =lockDao.findLocksBySearch(owner,locksn,orgid);
		ObjectNode tjson = null;
    	for(LockEntity elock : locklist) {
    		tjson = mapper.createObjectNode();
    		tjson.put("locksn", elock.getLocksn());
			tjson.put("operator", elock.getOperators());
			tjson.put("oper_reals", elock.getOper_reals());
			tjson.put("area", elock.getArea());
			tjson.put("orgname", elock.getOrgname());
			rootnode.add(tjson);
    	}
    	
    	res.put("status", "1");
    	res.put("datalist", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void getSingleLockList_template(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
		String locksn = "";
		String boxid = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			locksn =rootNode.get("locksn").asText();
			boxid =rootNode.get("boxid").asText();
		} catch (IOException e1) {
			res.put("status", "2");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}	
		List<LockEntity> locklist = null;
		locklist =lockDao.findAllotLocksBySearch(boxid,locksn,sentity.getOrg_id());
		ObjectNode tjson = null;
    	for(LockEntity elock : locklist) {
    		tjson = mapper.createObjectNode();
    		tjson.put("locksn", elock.getLocksn());
			tjson.put("operator", elock.getOperators());
			tjson.put("oper_reals", elock.getOper_reals());
			tjson.put("area", elock.getArea());
			tjson.put("boxid", elock.getBoxid());
			tjson.put("orgname", elock.getOrgname());
			rootnode.add(tjson);
    	}
    	
    	res.put("status", "1");
    	res.put("datalist", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void getDoubleLockList_template(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
		String locksn = "";
		String orgid = "";
		String owner = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			locksn =rootNode.get("locksn").asText();
			orgid =rootNode.get("orgid").asText();
			owner =rootNode.get("owner").asText();
		} catch (IOException e1) {
			res.put("status", "2");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}	
		List<LockEntity> locklist = null;
		locklist =lockDao.findDoubleLocksBySearch(owner,locksn,orgid);
		ObjectNode tjson = null;
    	for(LockEntity elock : locklist) {
    		tjson = mapper.createObjectNode();
    		tjson.put("locksn", elock.getLocksn());
			tjson.put("operator", elock.getOperators());
			tjson.put("oper_reals", elock.getOper_reals());
			tjson.put("area", elock.getArea());
			tjson.put("orgname", elock.getOrgname());
			rootnode.add(tjson);
    	}
    	
    	res.put("status", "1");
    	res.put("datalist", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void getUserNamelistByLock(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
		String locksn = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			locksn =rootNode.get("locksn").asText();
		} catch (IOException e1) {
			res.put("status", "2");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}	
		LockUserEntity lockuser = null;
		lockuser =lockDao.findLockUserByLock(locksn);
		String[] operators = lockuser.getOperators().split(",");
		ObjectNode tjson = null;
		UserRoleUnionOrg authuserinfo = null;
    	for(String authuser : operators) {
    		tjson = mapper.createObjectNode();
    		authuserinfo = userDao.findUserByName(authuser);
    		tjson.put("username", authuserinfo.getUsername());
			tjson.put("rolename", userDao.findRolenameByUserId(authuserinfo.getId()));
			tjson.put("oper_reals", authuserinfo.getRealname());
			tjson.put("orgname", authuserinfo.getOrg_name());
			rootnode.add(tjson);
    	}
    	
    	res.put("status", "1");
    	res.put("datalist", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void _lockstransfer(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	String owner = "";  
    	String newowner = "";   	
    	int offset = 0;
    	JsonNode childrenNode = null;
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		owner =rootNode.get("owner").asText();
    		newowner =rootNode.get("newowner").asText();
			childrenNode = rootNode.path("translocks");
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/锁具管理/锁具移交");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setMethod("_lockstransfer");
		//替换移交锁具的使用人
		Iterator<JsonNode> it = childrenNode.iterator();
		LockUserEntity lockuser = null;
		String[] tmpuser = null;
		String[] tmpoper = null;
		UserEntity ownerEntity = userDao.findByUserName(owner);
		if(ownerEntity == null) {
			resjson.put("status", "2");
			resjson.put("desc", "找不到使用人[" + owner + "]!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		UserEntity newownerEntity = userDao.findByUserName(newowner);
		if(newownerEntity == null) {
			resjson.put("status", "2");
			resjson.put("desc", "找不到移交人[" + newowner + "]!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		//查询使用人生效中的任务
		List<MissionEntity> mlist = missionDao.findActiveMissionByAuther(owner);
		String locksn = "";
    	while(it.hasNext()){
    		JsonNode jnode = it.next();
    		locksn = jnode.get("value").asText();
    		lockuser = lockDao.findLockUserByLock(locksn);
    		if(lockuser == null) {
    			resjson.put("status", "2");
				resjson.put("desc", "找不到授权锁具信息[" + locksn + "]!");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				deferredResult.setResult(mapper.writeValueAsString(resjson));
				return;
    		}
    		//判断锁具使用人列表是否有移交人
    		if(lockuser.getOperators().indexOf(newowner) > -1) {
    			//有
    			tmpuser = lockuser.getOperators().split(",");
    			tmpoper = lockuser.getOper_reals().split(",");
    			List<String> list=Arrays.asList(tmpuser);
    			List<String> operlist=Arrays.asList(tmpoper);
    			if(list.contains(owner)){
    				String tmpoperators = "";
    				String tmpoper_reals = "";
    				List<String> arrayList=new ArrayList<String>(list);
    				List<String> arrayoperList=new ArrayList<String>(operlist);
    		        arrayList.remove(owner);
    		        arrayoperList.remove(ownerEntity.getRealName());
    		        offset = 0;
    		        if(lockuser.getOpentype() == 1 && arrayList.size() < 2) {
    		        	resjson.put("status", "2");
    					resjson.put("desc", "锁具[" + lockuser.getLocksn() + "]开锁模式为双人,移交后使用人少于2人,移交失败!");
    					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    					deferredResult.setResult(mapper.writeValueAsString(resjson));
    					return;
    		        }
    		        for(String operator:arrayList ){
    		            if(offset == 0) {
    		            	tmpoperators = operator;
    		            }else {
    		            	tmpoperators += "," + operator;
    		            }
    		        }
    		        for(String operator:arrayoperList ){
    		            if(offset == 0) {
    		            	tmpoper_reals = operator;
    		            }else {
    		            	tmpoper_reals += "," + operator;
    		            }
    		        }
    		        lockuser.setOperators(tmpoperators);
    		        lockuser.setOper_reals(tmpoper_reals);
    			}
        		
    		}else {
    			//替换锁具的使用人及授权人
    			lockuser.setOperators(lockuser.getOperators().replace(owner, newowner));
    			lockuser.setOper_reals(lockuser.getOper_reals().replace(ownerEntity.getRealName(), newownerEntity.getRealName()));
    		}   		
    		
    		if(lockDao.updatelockuserActive(lockuser) == 0) {
    			resjson.put("status", "2");
				resjson.put("desc", "更新锁具[" + lockuser.getLocksn() + "]授权信息失败!");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				deferredResult.setResult(mapper.writeValueAsString(resjson));
				return;
    		}
    		
    		//变更任务详情列表信息    		
    		if(mlist.size() > 0) {
    			LockMissionDetailEntity detail = null;
    			for(MissionEntity mission:mlist) {
    				//查询任务详情列表指定锁信息
    				detail = missionDao.findDetailMissionByMissionIdAndlock(locksn, mission.getId());
    				//判断移交人是否是使用人
    				if(detail != null) {
    					if(detail.getAuthuser().indexOf(newowner) > -1) {
        	    			//移交人同时是使用人,删除使用人
        	    			tmpuser = detail.getAuthuser().split(",");
        	    			tmpoper = detail.getAuth_reals().split(",");
        	    			List<String> list=Arrays.asList(tmpuser);
        	    			List<String> operlist=Arrays.asList(tmpoper);
        	    			if(list.contains(owner)){
        	    				String tmpoperators = "";
        	    				String tmpoper_reals = "";
        	    				List<String> arrayList=new ArrayList<String>(list);
        	    				List<String> arrayoperList=new ArrayList<String>(operlist);
        	    		        arrayList.remove(owner);
        	    		        arrayoperList.remove(ownerEntity.getRealName());
        	    		        offset = 0;
        	    		        if(lockuser.getOpentype() == 1 && arrayList.size() < 2) {
        	    		        	resjson.put("status", "2");
        	    					resjson.put("desc", "锁具[" + lockuser.getLocksn() + "]开锁模式为双人,移交后任务授权人少于2人,移交失败!");
        	    					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        	    					deferredResult.setResult(mapper.writeValueAsString(resjson));
        	    					return;
        	    		        }
        	    		        for(String operator:arrayList ){
        	    		            if(offset == 0) {
        	    		            	tmpoperators = operator;
        	    		            }else {
        	    		            	tmpoperators += "," + operator;
        	    		            }
        	    		        }
        	    		        for(String operator:arrayoperList ){
        	    		            if(offset == 0) {
        	    		            	tmpoper_reals = operator;
        	    		            }else {
        	    		            	tmpoper_reals += "," + operator;
        	    		            }
        	    		        }
        	    		        detail.setAuthuser(tmpoperators);
        	    		        detail.setAuth_reals(tmpoper_reals);
        	    			}
        	        		
        	    		}else {
        	    			//替换锁具的使用人及授权人
        	    			detail.setAuthuser(detail.getAuthuser().replace(owner, newowner));
        	    			detail.setAuth_reals(detail.getAuth_reals().replace(ownerEntity.getRealName(), newownerEntity.getRealName()));
        	    		} 
        	    		
        	    		if(missionDao.updateLockMissionDetailAuther(detail) == -1) {
        	    			resjson.put("status", "2");
        					resjson.put("desc", "更新任务详情[" + detail.getLocksn() + "]授权信息失败!");
        					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        					deferredResult.setResult(mapper.writeValueAsString(resjson));
        					return;
        	    		}
    				}
    	    		
    			}
    		}
    	}
    	//更新任务列表授权信息
    	for(MissionEntity mission:mlist) {
    		if(mission.getMtype() == 0) {
    			//单人应急任务
    			mission.setAuthuser(newowner);
    			mission.setAuth_reals(newownerEntity.getRealName());
    			
    		}else if(mission.getMtype() == 2) {
    			//双人应急任务
    			if(mission.getAuthuser().indexOf(newowner) > -1) {
    				//双人模式应急任务只有授权2人,如移交人在该应急任务，则授权人少于2人,应急任务异常
    				resjson.put("status", "2");
					resjson.put("desc", "授权应急任务[" + mission.getCreatetime() + "]开锁模式为双人,移交后使用人少于2人,移交失败!");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					deferredResult.setResult(mapper.writeValueAsString(resjson));
					return;
    			}else {
    				mission.setAuthuser(mission.getAuthuser().replace(owner, newowner));
        			mission.setAuth_reals(mission.getAuth_reals().replace(ownerEntity.getRealName(), newownerEntity.getRealName()));
    			}
    		}else {
    			//单人和双人模式日常任务
    			//判断任务下是否还有该使用人的锁
    			if(missionDao.findDetailMissionByMissionIdAndAuther(owner, mission.getId()) == null) {
    				//没有了,替换授权人信息
    				//判断移交人是否在该任务
    				if(mission.getAuthuser().indexOf(newowner) > -1) {
    					//该任务已包含移交人,删除使用人
    					tmpuser = mission.getAuthuser().split(",");
    	    			tmpoper = mission.getAuth_reals().split(",");
    	    			List<String> list=Arrays.asList(tmpuser);
    	    			List<String> operlist=Arrays.asList(tmpoper);
    	    			if(list.contains(owner)){
    	    				String tmpoperators = "";
    	    				String tmpoper_reals = "";
    	    				List<String> arrayList=new ArrayList<String>(list);
    	    				List<String> arrayoperList=new ArrayList<String>(operlist);
    	    		        arrayList.remove(owner);
    	    		        arrayoperList.remove(ownerEntity.getRealName());
    	    		        offset = 0;
    	    		        for(String operator:arrayList ){
    	    		            if(offset == 0) {
    	    		            	tmpoperators = operator;
    	    		            }else {
    	    		            	tmpoperators += "," + operator;
    	    		            }
    	    		        }
    	    		        for(String operator:arrayoperList ){
    	    		            if(offset == 0) {
    	    		            	tmpoper_reals = operator;
    	    		            }else {
    	    		            	tmpoper_reals += "," + operator;
    	    		            }
    	    		        }
    	    		        mission.setAuthuser(tmpoperators);
    	    		        mission.setAuth_reals(tmpoper_reals);
    	    			}
    				}else {
    					mission.setAuthuser(mission.getAuthuser().replace(owner, newowner));
            			mission.setAuth_reals(mission.getAuth_reals().replace(ownerEntity.getRealName(), newownerEntity.getRealName()));
    				}
    				
    			}else {
    				//还有,增加移交人信息
    				//判断移交人是否在该任务
    				if(mission.getAuthuser().indexOf(newowner) > -1) {
    					//不需要更新
    					
    				}else {
    					mission.setAuthuser(mission.getAuthuser() + "," + newowner);
            			mission.setAuth_reals(mission.getAuth_reals() + "," + newownerEntity.getRealName());
    				}
    				
    			}
    		}
    		
    		if(missionDao.updatemission(mission) == 0) {
				resjson.put("status", "3");
				resjson.put("desc", "更新任务列表[" + mission.getCreatetime() + "]授权信息失败!");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				deferredResult.setResult(mapper.writeValueAsString(resjson));
				return;
			}
    	}
    	
    	resjson.put("status", "1");
    	resjson.put("desc", "锁具移交成功!");
    	ulog.setDescriptor("[" + ownerEntity.getRealName() + "]的锁具移交给[" + newownerEntity.getRealName() + "]!");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _lockstransfer_init(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{  

    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	resjson.put("status", "1");
    	resjson.put("desc", "成功初始化!");

		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public String getkeylist(String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	ArrayNode rootnode = mapper.createArrayNode();
    	com.fasterxml.jackson.databind.JsonNode rootNode;	
    	int pageNumber = 0;
    	int pageSize = 0;
    	String orgname = "";
    	String owner = "";
    	String keysn = "";
    	try {
			rootNode = mapper.readTree(jsonstr);
			pageNumber =rootNode.get("pageNumber").asInt();
			pageSize=rootNode.get("pageSize").asInt();
			orgname =rootNode.get("orgname").asText();
			owner =rootNode.get("owner").asText();
			keysn=rootNode.get("keysn").asText();
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		return mapper.writeValueAsString(resjson);
		}		
    	//判断用户是否为日常管理员
    	int totalcount = 0;
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	if(userDao.findRoleByUsername(sentity.getUsername()) < 3) {
    		//是日常管理员
    		List<KeyEntity> keylist = null;
    		if(userDao.isRootOrg(sentity.getOrg_id())) {
    			keylist = lockDao.findAllKeys(pageNumber,pageSize,orgname,owner,keysn);
            	totalcount = lockDao.getKeysCount(orgname,owner,keysn);
    		}else {
    			List<OrganizationEntity> suborgs = userDao.findSubOrg(sentity.getOrg_id());
            	keylist = lockDao.findAllKeys(pageNumber,pageSize,orgname,owner,keysn,suborgs);
            	totalcount = lockDao.getKeysCount(orgname,owner,keysn,suborgs);
    		}
        	
        	if(keylist != null && keylist.size()> 0){
    			ObjectNode tjson = null;
    			for(KeyEntity sys : keylist){
    				tjson = mapper.createObjectNode();
    				tjson.put("id", sys.getId());
        			tjson.put("descriptor", sys.getDescriptor());
        			tjson.put("keysn", sys.getKeysn());
        			tjson.put("owner", sys.getOwner());
        			tjson.put("ownername", sys.getOwnername());
        			tjson.put("createname", sys.getCreatename());
        			tjson.put("regdate", sdf.format(sys.getRegdate()));     
        			if(sys.getLastreport() != null) {
        				tjson.put("lastreport", sdf.format(sys.getLastreport())); 
        			}else {
        				tjson.put("lastreport", ""); 
        			}
        			tjson.put("orgname", sys.getOrgname());
        			tjson.put("electricity", sys.getElectricity());
        			tjson.put("orgid", sys.getOrgid());
        			rootnode.add(tjson);
        		}
    		} 
        	
    	}else {
    		//不是日常管理员
        	List<KeyEntity> keylist = lockDao.findKeysByUser(pageNumber,pageSize,keysn,sentity.getUsername());
        	if(keylist != null && keylist.size()> 0){
    			ObjectNode tjson = null;
    			for(KeyEntity sys : keylist){
    				tjson = mapper.createObjectNode();
    				tjson.put("id", sys.getId());
        			tjson.put("descriptor", sys.getDescriptor());
        			tjson.put("keysn", sys.getKeysn());
        			tjson.put("owner", sys.getOwner());
        			tjson.put("ownername", sentity.getRealName());
        			tjson.put("active", sys.getActive());
        			tjson.put("regdate", sdf.format(sys.getRegdate()));  
        			if(sys.getLastreport() != null) {
        				tjson.put("lastreport", sdf.format(sys.getLastreport())); 
        			}else {
        				tjson.put("lastreport", ""); 
        			}
        			tjson.put("orgname", sys.getOrgname());
        			tjson.put("electricity", sys.getElectricity());
        			tjson.put("orgid", sys.getOrgid());
        			rootnode.add(tjson);
        		}
    		} 
        	totalcount = lockDao.findKeysByUserCount(keysn,sentity.getUsername());
    	}
    	
    	
    	resjson.put("status", "1");
    	resjson.put("totalCount", totalcount);
    	resjson.put("pageSize", pageSize);
    	resjson.put("datalist", rootnode);
    	
    	return mapper.writeValueAsString(resjson);  
    }
    
    public void _insertkey(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request,HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	KeyEntity ekey = new KeyEntity();
    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String keysn = "";  
    	String orgid = "";
    	String descriptor = "";
    	String ckname = "";
    	String owner = "";
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		keysn =rootNode.get("keysn").asText();
    		owner = rootNode.get("owner").asText();
    		orgid = rootNode.get("orgid").asText();
			descriptor = rootNode.get("descriptor").asText();
			ckname = rootNode.get("ckname").asText(); 
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	

		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/钥匙管理/新增编辑");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_insertkey");
		ulog.setOrgid(sentity.getOrg_id());

		String uId = UUID.randomUUID().toString().replace("-", "");
		ekey.setId(uId);
		ekey.setCreatename(sentity.getUsername());
		ekey.setRegdate(date);
		ekey.setOwner(owner);;
		ekey.setCkname(ckname);
		ekey.setDescriptor(descriptor);
		ekey.setKeysn(keysn);
		ekey.setOrgid(orgid);
		ekey.setActive(0);
		int flag = lockDao.insertKey(ekey);
		if(flag == -1){
			resjson.put("status", "0");
			resjson.put("desc", "添加钥匙失败!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}else if(flag == 2) {
			resjson.put("status", "0");
			resjson.put("desc", "重复的钥匙识别码!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}
		
		resjson.put("status", "1");
		resjson.put("desc", "成功!");
		ulog.setDescriptor("钥匙[" + keysn + "]被添加");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);

		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _updatekey(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	String keysn = "";    	
    	String descriptor = "";
    	String orgid = "";
    	String owner = "";
    	String ckname = "";
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		keysn =rootNode.get("keysn").asText();
    		orgid =rootNode.get("org_id").asText();
    		owner =rootNode.get("owner").asText();
			descriptor = rootNode.get("descriptor").asText();
			ckname = rootNode.get("ckname").asText();
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/钥匙管理/新增编辑");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setMethod("_updatekey");

    	try{
    		KeyEntity elock = lockDao.findKeyBySn(keysn);
    		if(elock == null) {
    			resjson.put("status", "0");
    			resjson.put("desc", "找不到钥匙信息!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
    		}
    		XinLongUtil.xinLongUtil.printlog(log,"更新钥匙信息:"+ keysn);
    		if(!elock.getOwner().equals(owner)) {
    			ulog.setDescriptor("锁具[" + keysn + "]被编辑并移交给了[" + owner + "]!");
    		}else {
    			ulog.setDescriptor("锁具[" + keysn + "]被编辑!");
    		}
    		ulog.setCreate_check_userid(ckname);
			elock.setCkname(ckname);
			elock.setDescriptor(descriptor);
			elock.setOrgid(orgid);
			elock.setOwner(owner);
    		if(lockDao.updateKey(elock) == -1){
    			resjson.put("status", "0");
    			resjson.put("desc", "更新钥匙信息失败!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
    		}
    		
        	
    		
    	}catch(Exception e){
    		resjson.put("status", "2");
			resjson.put("desc", "未知异常!");
			ulog.setDescriptor(e.getMessage());
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			log.error(e.getMessage());
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	resjson.put("status", "1");
    	resjson.put("desc", "成功!");
    	
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _keyDelete(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode resjson = mapper.createObjectNode();  
		String keysn="";
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/钥匙管理/删除");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("_keyDelete");
		ulog.setOrgid(sentity.getOrg_id());
    	com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			keysn=rootNode.get("keysn").asText();
			ulog.setCreate_check_userid(rootNode.get("ckname").asText());
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}		
		/*resjson = XinLongUtil.OptAuth(id,jsonstr, sentity);
		if(!resjson.get("status").asText().equals("1210")){
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}*/		
    	
    	if(lockDao.deletekey(keysn) == -1){
    		resjson.put("status", "0");
    		resjson.put("desc", "删除钥匙失败!");
    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ulog.setDescriptor("删除钥匙失败");
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
    	}
    	
		ulog.setDescriptor("钥匙[" + keysn + "]被删除");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
    	resjson.put("status", "1");
		resjson.put("desc", "成功!");
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _keyOff(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode resjson = mapper.createObjectNode();  
		String keysn="";
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/钥匙管理/注销");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("_keyOff");
		ulog.setOrgid(sentity.getOrg_id());
    	com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			keysn=rootNode.get("keysn").asText();
			ulog.setCreate_check_userid(rootNode.get("ckname").asText());
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}		
		
    	if(lockDao.offkey(keysn,date,sentity.getUsername()) == -1){
    		resjson.put("status", "0");
    		resjson.put("desc", "注销钥匙失败!");
    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ulog.setDescriptor("注销钥匙失败");
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
    	}
    	
		ulog.setDescriptor("钥匙[" + keysn + "]被注销");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
    	resjson.put("status", "1");
		resjson.put("desc", "成功!");
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void addtestlock(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request,HttpSession session) throws JsonProcessingException{  
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	LockEntity elock = null;
    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String locksn = ""; 
    	String orgid = "";
    	int number = 0;
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		locksn =rootNode.get("locksn").asText();
    		orgid = rootNode.get("orgid").asText();
			number = rootNode.get("number").asInt();  
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	

		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Long startsn = Long.valueOf(locksn,16) - 1;
		for(int i=0;i<number;i++) {
			startsn += 1;
			elock = new LockEntity();
			elock.setId(UUID.randomUUID().toString().replace("-", ""));
			elock.setRegtime(dateFormat.format(date));
			elock.setArea("");
			elock.setBoxid("");
			elock.setCname("");
			elock.setDescriptor("");
			elock.setLocksn(Long.toHexString(startsn));
			elock.setOpentype(0);
			elock.setLocktype(3);
			elock.setOrgid(orgid);
			elock.setAuthed(0);
			int flag = lockDao.savelock(elock);
			if(flag == 0){
				resjson.put("status", "0");
				resjson.put("desc", "添加锁具失败!");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    		return;
			}else if(flag == 2) {
				resjson.put("status", "0");
				resjson.put("desc", "重复的锁具识别码[" + Long.toHexString(startsn) + "]!");
				deferredResult.setResult(mapper.writeValueAsString(resjson));
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    		return;
			}
			
			LockUserEntity lockuser = new LockUserEntity();
			lockuser.setId(UUID.randomUUID().toString().replace("-", ""));
			lockuser.setLocksn(Long.toHexString(startsn));
			lockuser.setOperators("");
			lockuser.setOper_reals("");
			lockuser.setActive(0);
			lockuser.setOpentype(0);
			lockuser.setLocktype(3);
			if(lockDao.insertLockuser(lockuser) == 0) {
				resjson.put("status", "0");
				resjson.put("desc", "添加锁具使用人信息失败!");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    		return;
			}
			
		}

		resjson.put("status", "1");
		resjson.put("desc", "成功!");

		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    	
    }

}
